package com.smart.tool.transaction;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.transaction.TransactionStatus;

/**
 * @Author gao.gwq
 * @Version TranscationContext.java, v 0.1 2024年01月25日 16:35 gao.gwq
 * @Description: TODO 事务上下文参数传递
 */

public class TransactionContext<T> {


    /**
     * 事务
     */
    private final TransactionStatus transactionStatus;

    private final String trancationId;

    /**
     * 执行抛出异常的信息
     */
    private Throwable throwable;
    /**
     * 执行上下文参数传递
     * 如果需要传递参数，请使用addParam方法，需要自己进行填充值
     */
    private Map<String,Object> paramMap;

    /**
     * 默认是否成功
     * 事务抛出异常时，会将该字段设置为false。系统默认 抛出异常时 是失败的。
     * 可以根据本字段来判断事务是否成功
     */
    private boolean isSucess = true;

    /**
     * 事务状态 在afterCompletion 使用
     * STATUS_COMMITTED = 0 事务提交
     * STATUS_ROLLED_BACK = 1 回滚
     * STATUS_UNKNOWN = 2 未知状态 挂起等
     */
    private Integer status;



    private Boolean readOnly;

    /**
     * 如果存在返回值,则会把对应的返回值放到result中
     */
    private T result;

    public T getResult() {
        return result;
    }

    public void setResult(T result) {
        this.result = result;
    }

    public Boolean getReadOnly() {
        return readOnly;
    }

    public void setReadOnly(Boolean readOnly) {
        this.readOnly = readOnly;
    }


    public TransactionContext(TransactionStatus transactionStatus, String trancationId) {
        this.transactionStatus = transactionStatus;
        this.trancationId = trancationId;
        paramMap = new ConcurrentHashMap<>();
    }

    public TransactionStatus getTransactionStatus() {
        return transactionStatus;
    }

    public boolean isSucess() {
        return isSucess;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public void setSucess(boolean sucess) {
        isSucess = sucess;
    }

    public String getTrancationId() {
        return trancationId;
    }

    public Object getParam(String key){
        return paramMap.get(key);
    }

    public void addParam(String key,Object value){
        paramMap.put(key,value);
    }

    public Throwable getThrowable() {
        return throwable;
    }

    public void setThrowable(Throwable throwable) {
        this.throwable = throwable;
    }
}
